using AutoMapper;
using FluentValidation;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Entites;
using Zhaoxi.Zhihu.Infrastructure;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Repositoy;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;

namespace Zhaoxi.Zhihu.UseCases.Questions.Command;

[Authorize]
public record CreateQuestionCommand(string Title, string? Description) : ICommand<Result<int>>;

public class CreateQuestionCommandValidator : AbstractValidator<CreateQuestionCommand>
{
   public CreateQuestionCommandValidator()
   {
      RuleFor(Command => Command.Title)
         .Cascade(CascadeMode.Stop)
         .NotEmpty()
         .Length(6, DataSchemaConstans.DefaultQuestionTitleLength)
         .Must(t => t.EndsWith("?") || t.EndsWith("？")).WithMessage("问题必须以问号结尾");

      RuleFor(Command => Command.Description)
         .MaximumLength(DataSchemaConstans.DefaultQuestionDescriptionLength);
   }
}

public class CreateQuestionCommandHandler(IRepository<Question> questions,IMapper mapper)
   : ICommandHandler<CreateQuestionCommand, Result<int>>
{
   public async Task<Result<int>> Handle(CreateQuestionCommand request, CancellationToken cancellationToken)
   {
      var question = mapper.Map<Question>(request);
      questions.Add(question);
      await questions.SaveChangesAsync(cancellationToken);
      return Result.Success(question.Id);
   }
}